﻿using System;
using System.Linq;
using Csla;
using Csla.Data;
using BizControl.DalLinq;
using BizControl.Library.Security;
using BizControl.Library.BusinessObjects.Models;
using BizControl.Library.BusinessObjects.People;
using BizControl.Library.Criterias;
using BizControl.Resources;
using System.Security;
using System.Collections.Generic;

namespace BizControl.Library.BusinessObjects.Activities
{
  [Serializable()]
  public class IndependentActivityListForActivity : ReadOnlyListBase<IndependentActivityListForActivity, ActivityInfo>
  {
    internal void AllowChange()
    {
      IsReadOnly = false;
    }

    internal void ForbidChange()
    {
      IsReadOnly = true;
    }

    #region  Factory Methods

    public static IndependentActivityListForActivity NewIndependentActivityListForActivity()
    {
      return DataPortal.Create<IndependentActivityListForActivity>();
    }

    public static IndependentActivityListForActivity GetIndependentActivityListForActivity(ActivityBO activity)
    {
      var person = ((BizControlPrincipal)ApplicationContext.User).Person;
      var model = ((BizControlPrincipal)ApplicationContext.User).Model;
      return DataPortal.Fetch<IndependentActivityListForActivity>(activity);
    }

    private static Guid GetAncestor(Guid activityId, ContextManager<BusinessControl2DataContext> ctx)
    {
      var ancestor = (from l in ctx.DataContext.ActivityLinks
                      where l.Activity2 == activityId
                      select l.Activity1).FirstOrDefault();
      Guid ancestor2 = ancestor;
      while (ancestor2 != Guid.Empty)
      {
        ancestor2 = (from l in ctx.DataContext.ActivityLinks
                     where l.Activity2 == ancestor
                     select l.Activity1).FirstOrDefault();
        if (ancestor2 != Guid.Empty) ancestor = ancestor2;
      }
      return ancestor;
    }

    #endregion

    #region  Data Access

    private void DataPortal_Create()
    {
    }

    private void DataPortal_Fetch(ActivityBO activity)
    {
      RaiseListChangedEvents = false;
      IsReadOnly = false;
      this.AddRange(IndependentActivityList.GetIndependentActivityList());
      Guid ancestorId = Guid.Empty;
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        ancestorId = GetAncestor(activity.ActivityId, ctx);
      }
      foreach (var independentActivity in this)
      {
        if (independentActivity.Id == activity.ActivityId || independentActivity.Id == ancestorId)
        {
          Remove(independentActivity);
          break;
        }
      }
      IsReadOnly = true;
      RaiseListChangedEvents = true;
    }

    #endregion

  }
}
